package com.glory.brepda.activity.lanjian.hdg;

import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.entity.HdgLotRegisterQueryResEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 烘烤/抖动/过回流焊 批次登记页面
 */
public class HdgLotRegisterActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;

    @BindView(R.id.etLotID)
    FreeUI_ClearEditText etLotID;

    @BindView(R.id.etProductModule)
    FreeUI_ClearEditText etProductModule;

    @BindView(R.id.etMainMatType)
    FreeUI_ClearEditText etMainMatType;

    @BindView(R.id.etMainQty)
    FreeUI_ClearEditText etMainQty;

    @BindView(R.id.etOperator_ID)
    FreeUI_ClearEditText etOperator_ID;

    @BindView(R.id.optionList)
    FrameLayout optionList;

    @BindView(R.id.etRequirement)
    FreeUI_ClearEditText etRequirement;

    @BindView(R.id.ivHdgArrow)
    ImageView ivHdgArrow;

    @BindView(R.id.etRegisterDate)
    FreeUI_ClearEditText etRegisterDate;

    @BindView(R.id.etComment)
    FreeUI_ClearEditText etComment;

    private FreeUI_GeneralPop optionPop;

    private HdgLotRegisterQueryResEntity entity;

    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_hdg_lot_register;
    }

    @Override
    protected void initView() {
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        // 初始化操作员 ，为操作用户
        etOperator_ID.setText(Constant.CURRENT_USER);
        setMainLayout(llMain);

        // 初始化下拉組件，监听
        // ①组件监听的方式
        optionList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (optionPop != null) {
                    if (optionPop.isShowing()) {
                        optionPop.dismiss();
                    }
                } else {
                    // todo: 使用 SharedPreferences 将列表信息存储到本地 ， 方便产线修改可用选项
                    optionPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), optionList.getWidth(), new ArrayList<String>(Arrays.asList("烘烤","抖动","过回流焊","低良复测")), ivHdgArrow, (ty, i) -> {
                        etRequirement.setText(ty);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivHdgArrow);
                optionPop.showAsDropDown(optionList, 0, 0);
            }
        });

        // 初始化日期 ，默认为当前时间
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String SEND_TIME = format.format(new Date());
        etRegisterDate.setText(SEND_TIME);

        initEdit(etLotID, sa -> {
            search();
        });

    }

    @Override
    protected void initData() {
    }

    @OnClick({R.id.tvBaseSubmit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                submit();
                break;
        }
    }
    private void btnClean1(){
        // 其他消息输入框清空
        etLotID.setText(null);
        etProductModule.setText(null);
        etMainMatType.setText(null);
        etMainQty.setText(null);
        etRequirement.setText(null);
        etComment.setText(null);

        // 时间重设
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String SEND_TIME = format.format(new Date());
        etRegisterDate.setText(SEND_TIME);
    }

    // 提交
    private void submit(){
        // 参数校验
        if(getText(etLotID).equals("")){
            showToast("请先扫描批次信息", false);
            return;
        }

        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    showToast("批次登记成功", true);
                    btnClean1();
                    etLotID.requestFocus();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(), "HDG_LOT_REGISTER");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTION_TYPE", "LR_SAVE");
        map.addProperty("LOT_ID", getText(etLotID));
        map.addProperty("LR_REQUIREMENT", getText(etRequirement));
        map.addProperty("LR_OPERATOR_ID", getText(etOperator_ID));
        map.addProperty("LR_REGISTER_DATE", Objects.requireNonNull(etRegisterDate.getText(),"登记日期不能为空").toString());
        map.addProperty("LR_COMMENT", getText(etComment));
        NetUtils.requestPostNet("IF.HDG_LOT_REGISTER", "Common", HdgLotRegisterActivity.this, map, callBack);
    }

    // 扫描批次
    private void search(){
        FreeUI_EntityCallBack<BaseResponseBean<HdgLotRegisterQueryResEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<HdgLotRegisterQueryResEntity>>
                (new TypeToken<BaseResponseBean<HdgLotRegisterQueryResEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<HdgLotRegisterQueryResEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    entity = response.body().getResponse().getBody();
                    inputValue(entity);
                    showToast("请求成功", true);
                    etLotID.requestFocus();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<HdgLotRegisterQueryResEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "请求失败");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("LOT_ID", getText(etLotID));
        map.addProperty("ACTION_TYPE", "QUERY");
        NetUtils.requestPostNet("IF.HDG_LOT_REGISTER", "Common", HdgLotRegisterActivity.this, map, callBack);
    }

    // ResponseEntity to value
    private void inputValue(HdgLotRegisterQueryResEntity entity){
        etLotID.setText(entity.getLOTID());
        etMainMatType.setText(entity.getMAINMATTYPE());
        etMainQty.setText(String.valueOf(entity.getMAINQTY()));
        etProductModule.setText(entity.getPRODUCTMODEL());
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("批次记录登记");
        return new FreeUI_AddViewEntity("header", llMain);
    }

    // 判断是否为数字
    boolean isNumeric(String str) {
        if (str == null) return false;
        str = str.trim();
        return str.matches("^-?\\d+(\\.\\d+)?$");
    }
}